package web.admin.shop.product;


import domain.shop.Product;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class provides administration of products
 */
public final class ProductAdminPanel extends Panel {

    @SpringBean
    private ShopAdminService shopAdminService;
    private Panel empty = new EmptyPanel("current");
    private Panel current = empty;
    private static Logger logger = Logger.getLogger(ProductAdminPanel.class.getName());
    private ProductsDataTablePanel productsDataTablePanel;

    public ProductAdminPanel(String id) {
        super(id);
        add(current);
        current.setOutputMarkupId(true);
        productsDataTablePanel = new ProductsDataTablePanel("list", this);
        add(productsDataTablePanel);

        Form form = new Form("form");
        Link addProduct = new Link("addProduct") {

            @Override
            public void onClick() {
                Product product = null;
                try {
                    product = shopAdminService.createProduct();
                    replacePanel(product.getId());

                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    error(getLocalizer().getString("system.error", this));

                }
            }
        };
        form.add(addProduct);
        add(form);
    }


    public void replacePanelToEmpty() {
        current.replaceWith(empty);
        current = empty;
    }

    public void replacePanel(final Long productId, AjaxRequestTarget target) {
        replacePanel(productId, target, this);
    }

    private void replacePanel(final Long productId, AjaxRequestTarget target, final ProductAdminPanel parent) {
        Panel panel =
                new AjaxLazyLoadPanel("current") {
                    @Override
                    public Component getLazyLoadComponent(String id) {
                        return new ProductPanel(id, productId, parent);

                    }

                };
        current.replaceWith(panel);
        current = panel;
        if (target != null) {
            target.addComponent(current);
        }
    }

    public void replacePanel(Long id) {
        replacePanel(id, null, this);
    }

    public void detachProductsModel() {
        productsDataTablePanel.detachTableModel();
    }
}
